//
//  JDShopcartTableViewCell.swift
//  DragonWallet
//
//  Created by volantPig on 2024/4/2.
//

import UIKit
import SwiftyJSON

class JDShopcartTableViewCell: UITableViewCell {

    var calculateCallBack: (()->Void)?
    
    var shopcartModel: JDShopCartGoodsModel? {
        didSet {
            self.refreshData()
        }
    }
    
    var containerView: UIView?
    var checkboxButton: UIButton?
    var productImgV: UIImageView?
    var memberGoodsImageV: UIImageView?
    
    var productNameLabel: UILabel?
    var productSpecLabel: UILabel?
    var priceLabel: UILabel?
    
    var numberView: JDNumberInputView?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.contentView.backgroundColor = color("#F5F6F8")
        self.setupUIElements()
    }
    
    func setupUIElements() {
        self.containerView = UIView()
        self.contentView.addSubview(self.containerView!)
        self.containerView?.snp.makeConstraints({ make in
            make.top.bottom.equalTo(self.contentView)
            make.left.equalTo(self.contentView).offset(12)
            make.right.equalTo(self.contentView).offset(-12)
        })
        self.containerView?.backgroundColor = .white
        
        self.checkboxButton = UIButton(type: .custom)
        self.containerView?.addSubview(self.checkboxButton!)
        self.checkboxButton?.snp.makeConstraints({ make in
            make.centerY.equalTo(self.containerView!)
            make.left.equalTo(self.containerView!).offset(12)
            make.size.equalTo(CGSize(width: 20, height: 20))
        })
        //        self.checkboxButton?.backgroundColor = .green
        self.checkboxButton?.addTarget(self, action: #selector(checkboxClicked), for: .touchUpInside)
        self.checkboxButton?.setImage(UIImage(named: "shopcart_unSelected")?.withRenderingMode(.alwaysOriginal), for: .normal)
        
        self.productImgV = UIImageView()
        self.containerView?.addSubview(self.productImgV!)
        self.productImgV?.snp.makeConstraints({ make in
            make.left.equalTo(self.checkboxButton!.snp.right).offset(20)
            make.centerY.equalTo(self.containerView!)
            make.size.equalTo(CGSize(width: 84, height: 84))
        })
        
        self.memberGoodsImageV = UIImageView()
        self.containerView?.addSubview(self.memberGoodsImageV!)
        self.memberGoodsImageV?.snp.makeConstraints { make in
            make.trailing.equalTo(self.productImgV!)
            make.bottom.equalTo(self.productImgV!)
            make.size.equalTo(CGSize(width: 58, height: 16))
        }
        self.memberGoodsImageV?.image = UIImage(named: "memberGoods")
        self.memberGoodsImageV?.isHidden = true
        
        self.productNameLabel = UILabel()
        self.containerView?.addSubview(self.productNameLabel!)
        self.productNameLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.productImgV!.snp.right).offset(10)
            make.top.equalTo(self.productImgV!).offset(-4)
            make.right.equalTo(self.containerView!).offset(-15)
            make.height.equalTo(22)
        })
        self.productNameLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"), numberOfLines: 0)
        self.productNameLabel?.text = ""
        
        self.productSpecLabel = UILabel()
        self.containerView?.addSubview(self.productSpecLabel!)
        self.productSpecLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.productNameLabel!)
            make.top.equalTo(self.productNameLabel!.snp.bottom).offset(6)
            make.height.equalTo(18)
        })
        self.productSpecLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 13, weight: .regular), textColor: color("#333333"))
        self.productSpecLabel?.text = "规格：黑色"
        
        self.priceLabel = UILabel()
        self.containerView?.addSubview(self.priceLabel!)
        self.priceLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.productNameLabel!)
            make.bottom.equalTo(self.productImgV!).offset(-2)
            make.height.equalTo(22)
        })
        self.priceLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .semibold), textColor: color("#333333"))
        self.priceLabel?.text = "￥194.00"
        self.priceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 16, weight: .semibold))
        
        self.numberView = JDNumberInputView()
        self.containerView?.addSubview(self.numberView!)
        self.numberView?.snp.makeConstraints({ make in
            make.right.equalTo(self.containerView!).offset(-12)
            make.bottom.equalTo(self.containerView!).offset(-16)
            make.width.equalTo(88)
            make.height.equalTo(28)
        })
        self.numberView?.addborder()
        
        
        self.numberView?.plusActionBlock = {[weak self] number in
            self?.updatePrice(number)
        }
        
        self.numberView?.minusActionBlock = { [weak self] number in
            self?.updatePrice(number)
        }
        
        /**
         我想写一个方法 大概是这个样子的
         self.numberView.add = { number in
            number += (具体每次加的数值)
            model.number = number
         }
         减法也是类似的样子，但是这里涉及到的问题就是引用的问题
         其实也可以，在numberView的number的didSet之类的方法里，去
         */
        
    }
    
    func updatePrice(_ number: Int) {
        self.shopcartModel?.count = number
//        let priceInfo = Float((self.shopcartModel?.salePrice ?? 0) * number)/1000.0
//        self.priceLabel?.text = String(format: "￥%.2f", priceInfo)
//        self.priceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 16, weight: .semibold))
        
        // 修改购物车数量
        // TODO: 这个地方，考虑下，怎么再优化一下
        var params = [String: Any]()
        params["goodsId"] = self.shopcartModel?.goodsId
        params["count"] = number
        params["goodsSkuId"] = self.shopcartModel?.goodsSkuId
        JDNetWorkRequest(.modifyShopcartGoodsCount(params)) { responseStr in
        
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                self.calculateCallBack?()
                printLog("修改成功")
            }
              
        } failure: { error in
            
        } error: { errorCode in
            
        }
        
    }
    

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    func refreshData() {
        guard let confirmModel = self.shopcartModel else { return }
        
        if confirmModel.goodsMainImgUrl?.hasPrefix("http") ?? false  {
            self.productImgV?.kf.setImage(with: URL(string: confirmModel.goodsMainImgUrl ?? ""),placeholder: UIImage(named: "loading_placeholder"))
        } else {
            self.productImgV?.downloadImage(confirmModel.goodsMainImgUrl ?? "" )
        }
        
        self.productNameLabel?.text = confirmModel.goodsName
        self.productSpecLabel?.text = String(format: "规格：%@", confirmModel.specificationName ?? "默认规格")
  
//        let priceInfo = Float((confirmModel.salePrice ?? 0) * (confirmModel.count ?? 0))/1000.0
        self.priceLabel?.text = String(format: "￥%@", confirmModel.salePriceText ?? "0.00")
        self.priceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 16, weight: .semibold))
        
        self.numberView?.showNumber = confirmModel.count ?? 0
        self.numberView?.numberInputView.text = String(format: "%zd", confirmModel.count ?? 0)
        
        if confirmModel.isSelected {
            self.checkboxButton?.setImage(UIImage(named: "shopcart_Selected")?.withRenderingMode(.alwaysOriginal), for: .normal)
        } else {
            self.checkboxButton?.setImage(UIImage(named: "shopcart_unSelected")?.withRenderingMode(.alwaysOriginal), for: .normal)
        }
        
        /// 是否是会员上皮
        if confirmModel.goodsMemberLevel == "2" {
            self.memberGoodsImageV?.isHidden = false
        } else {
            self.memberGoodsImageV?.isHidden = true
        }
        
//        if self.shopcartModel?.isSelected ?? false {
//            self.shopcartModel?.isSelected = false
//            self.checkboxButton?.setImage(UIImage(named: "shopcart_unSelected")?.withRenderingMode(.alwaysOriginal), for: .normal)
//        } else {
//            self.shopcartModel?.isSelected = true
//            self.checkboxButton?.setImage(UIImage(named: "shopcart_Selected")?.withRenderingMode(.alwaysOriginal), for: .normal)
//        }
        
    }

}

// MARK: Action
extension JDShopcartTableViewCell {
    @objc func checkboxClicked() {
        if self.shopcartModel?.isSelected ?? false {
            self.shopcartModel?.isSelected = false
            self.checkboxButton?.setImage(UIImage(named: "shopcart_unSelected")?.withRenderingMode(.alwaysOriginal), for: .normal)
        } else {
            self.shopcartModel?.isSelected = true
            self.checkboxButton?.setImage(UIImage(named: "shopcart_Selected")?.withRenderingMode(.alwaysOriginal), for: .normal)
        }
        self.calculateCallBack?()
    }
}
